package com.libui.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*

object PermissionSettingUtils {
    /**
     * 跳转至权限设置页面
     *
     * @param activity
     */
    fun goPermissionSet(activity: Activity) {
        val name = Build.MANUFACTURER
        when (name.lowercase(Locale.getDefault())) {
            "huawei" -> goHuaWeiManager(activity)
            "vivo" -> goVivoManager(activity)
            "oppo" -> goOppoManager(activity)
            "coolpad" -> goCoolpadManager(activity)
            "meizu" -> goMeizuManager(activity)
            "xiaomi" -> goXiaoMiManager(activity)
            "samsung" -> goSangXinManager(activity)
            "sony" -> goSonyManager(activity)
            "lg" -> goLGManager(activity)
            "letv", "lemobile" -> goLetvManager(activity)
            else -> goIntentSetting(activity)
        }
    }

    private fun goLetvManager(activity: Activity) {
        try {
            val intent = Intent(activity.packageName)
            val comp = ComponentName(
                "com.letv.android.letvsafe",
                "com.letv.android.letvsafe.PermissionAndApps"
            )
            intent.component = comp
            activity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            goIntentSetting(activity)
        }
    }

    private fun goLGManager(activity: Activity) {
        try {
            val intent = Intent(activity.packageName)
            val comp = ComponentName(
                "com.android.settings",
                "com.android.settings.Settings\$AccessLockSummaryActivity"
            )
            intent.component = comp
            activity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            goIntentSetting(activity)
        }
    }

    private fun goSonyManager(activity: Activity) {
        try {
            val intent = Intent(activity.packageName)
            val comp = ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity")
            intent.component = comp
            activity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            goIntentSetting(activity)
        }
    }

    private fun goHuaWeiManager(activity: Activity) {
        try {
            val intent = Intent(activity.packageName)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val comp = ComponentName(
                "com.huawei.systemmanager",
                "com.huawei.permissionmanager.ui.MainActivity"
            )
            intent.component = comp
            activity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            goIntentSetting(activity)
        }
    }

    private fun getMiuiVersion(): String? {
        val propName = "ro.miui.ui.version.name"
        val line: String
        var input: BufferedReader? = null
        try {
            val p = Runtime.getRuntime().exec("getprop $propName")
            input = BufferedReader(
                InputStreamReader(p.inputStream), 1024
            )
            line = input.readLine()
            input.close()
        } catch (ex: IOException) {
            ex.printStackTrace()
            return null
        } finally {
            try {
                input!!.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return line
    }

    private fun goXiaoMiManager(activity: Activity) {
        val rom = getMiuiVersion()
        val intent = Intent()
        when (rom) {
            "V6", "V7" -> {
                intent.action = "miui.intent.action.APP_PERM_EDITOR"
                intent.setClassName(
                    "com.miui.securitycenter",
                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity"
                )
                intent.putExtra("extra_pkgname", activity.packageName)
            }
            "V8", "V9" -> {
                intent.action = "miui.intent.action.APP_PERM_EDITOR"
                intent.setClassName(
                    "com.miui.securitycenter",
                    "com.miui.permcenter.permissions.PermissionsEditorActivity"
                )
                intent.putExtra("extra_pkgname", activity.packageName)
            }
            else -> {
                goIntentSetting(activity)
            }
        }
    }

    private fun goMeizuManager(activity: Activity) {
        try {
            val intent = Intent("com.meizu.safe.security.SHOW_APPSEC")
            intent.addCategory(Intent.CATEGORY_DEFAULT)
            intent.putExtra("packageName", activity.packageName)
            activity.startActivity(intent)
        } catch (localActivityNotFoundException: ActivityNotFoundException) {
            localActivityNotFoundException.printStackTrace()
            goIntentSetting(activity)
        }
    }

    private fun goSangXinManager(activity: Activity) {
        // 三星4.3可以直接跳转
        goIntentSetting(activity)
    }

    private fun goIntentSetting(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", activity.packageName, null)
        intent.data = uri
        try {
            activity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun goOppoManager(activity: Activity) {
        doStartApplicationWithPackageName("com.coloros.safecenter", activity)
    }

    private fun goVivoManager(activity: Activity) {
        doStartApplicationWithPackageName("com.bairenkeji.icaller", activity)
    }

    private fun goCoolpadManager(activity: Activity) {
        doStartApplicationWithPackageName("com.yulong.android.security:remote", activity)
    }

    @SuppressLint("QueryPermissionsNeeded")
    private fun doStartApplicationWithPackageName(packageName: String, activity: Activity) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        var packageInfo: PackageInfo? = null
        try {
            packageInfo = if (Build.VERSION.SDK_INT >= 33) {
                activity.packageManager.getPackageInfo(
                    packageName,
                    PackageManager.PackageInfoFlags.of(0)
                )
            } else {
                activity.packageManager.getPackageInfo(packageName, 0)
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        if (packageInfo == null) {
            return
        }
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        val resolveIntent = Intent(Intent.ACTION_MAIN, null)
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resolveIntent.setPackage(packageInfo.packageName)
        // 通过getPackageManager()的queryIntentActivities方法遍历
        val resolveInfoList = if (Build.VERSION.SDK_INT >= 33) {
            activity.packageManager
                .queryIntentActivities(resolveIntent, PackageManager.ResolveInfoFlags.of(0))
        } else {
            activity.packageManager
                .queryIntentActivities(resolveIntent, 0)
        }
        println("resolve info List" + resolveInfoList.size)
        for (i in resolveInfoList.indices) {
            println("PermissionPageManager" + resolveInfoList[i].activityInfo.packageName + resolveInfoList[i].activityInfo.name)
        }
        val resolveInfo = resolveInfoList.iterator().next()
        if (resolveInfo != null) {
            // LAUNCHER Intent
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)

            // 设置ComponentName参数1:packageName参数2:MainActivity路径
            intent.component =
                ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name)
            try {
                activity.startActivity(intent)
            } catch (e: Exception) {
                goIntentSetting(activity)
                e.printStackTrace()
            }
        }
    }
}